package com.chis.netty.restful.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

public class RestServer {

    /**
     * win系统入口
     * @param args args
     * @throws Exception 系统异常
     */
    public static void main(String[] args) throws Exception {
        new RestServer().bind(9092);
    }

    /**
     * @param port 端口
     * @throws Exception 系统异常
     */
    private void bind(int port) throws Exception {

        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //JVM销毁前执行
        Runtime.getRuntime().addShutdownHook(new Thread(){
            public void run(){
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG,500).childOption(ChannelOption.SO_KEEPALIVE,true);
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new RestServerInitializer());
            System.out.println("服务端开启等待客户端连接 ... ...");
            Channel ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }




    }

}
